<template>
  <div class="inout-box">
    <el-dialog width="600px" :title="dialogTitle" v-model="dialogFormVisible" :close-on-click-modal="false" :draggable="true"
      @close="dialogClose">
      <div class="content-box">
        <div class="content-item">
          <p>
            1、先下载导入模版，根据模版提示填写好内容后再上传
          </p>
          <el-button style="margin-top:20px;" @click="templateDownLoad" :loading="loading">下载模板</el-button>
        </div>
        <div class="content-item">
          <p>
            2、上传填写好后的文件，文件格式xls、xlsx格式的文件
          </p>
          <div class="upload-box">
            <el-button @click="uploadHandle">选择上传的文件</el-button>
            <input ref="uploadInputRef" style="display:none" type="file"
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              @change="uploadChange">
            <div v-show="fileForm.file" class="upload-file">
              <span>{{ fileForm.fileName }}</span>
              <el-icon class="delete-btn" @click="deleteFile">
                <Close />
              </el-icon>
            </div>
          </div>
        </div>
        <div v-show="errmsg" style="color:#f56c6c;">{{ errmsg }}</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div></div>
          <div>
            <el-button @click="dialogFormVisible = false">关闭</el-button>
            <el-button v-show="activeName == 1" type="primary" @click="submitHandle">
              {{ activeName == 1 ? '上传' : '' }}
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs, watch } from 'vue'
import { BlobDownLoad, successDeal, warningDeal, getStore } from '@/utils/utils'
import api from './api'
import { useStateStore } from '@/store'
import axios from "axios"
export default {
  setup(props, context) {
    const store = useStateStore()

    const uploadInputRef = ref(null)

    const state = reactive({
      loading: false,
      dialogType: null,
      dialogTitle: '',
      activeName: 1,
      dialogFormVisible: false,
      fileForm: {},
      errmsg: null,
    })

    watch(() => state.fileForm, (newVal, oldVal) => {
      if (newVal.file) {
        state.errmsg = null
      } else {
        state.errmsg = '请选择上传文件'
      }
    })

    function dialogShow(i) {
      state.dialogType = i
      if (i == 1) {
        state.dialogTitle = '新增商品导入'
      } else if (i == 2) {
        state.dialogTitle = '修改商品导入'
      }
      state.errmsg = null
      state.dialogFormVisible = true
    }

    function tabChange(e) {
      //tabs改变
    }

    function dialogClose() {
      //弹窗关闭
      deleteFile()
    }

    function templateDownLoad() {
      if (state.loading) return
      let apiName = ''
      if (state.dialogType == 1) {
        apiName = 'addUploadTemplete'
      } else if (state.dialogType == 2) {
        apiName = 'modifyUploadTemplete'
      }
      state.loading = true
      api[apiName]({ responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
        state.loading = false
      }).catch(err => {
        console.log(err)
        state.loading = false
      })
    }

    function uploadHandle() {
      uploadInputRef.value.click()
    }

    //上传文件
    function uploadChange(e) {
      const myArr = e.target.files[0].name.split('.')
      if (myArr[myArr.length - 1] != 'xls' && myArr[myArr.length - 1] != 'xlsx') {
        state.errmsg = '请上传xls、xlsx格式的文件'
        return
      }
      state.fileForm = {}
      state.fileForm.file = e.target.files[0]
      state.fileForm.fileName = e.target.files[0].name
      uploadInputRef.value.value = ''
    }

    async function uploadFile() {
      const token = window.localStorage.getItem("USER_TOKEN") || '';
      const uesrInfo = getStore("USER_INFO") || {};
      const Authorization = getStore("USER_AUTHOR") || {
        Authorization: `'','','',3,20,''`,
      };
      let param = new FormData()
      param.append('file', state.fileForm.file, state.fileForm.fileName)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: token ? `Bearer ${token}` : '',
          username: uesrInfo.username || '',
          Authorization: Authorization.Authorization,
          platformHeadType: store.getPlatformHeadType,
        }
      }
      let apiUrl = ''
      if (state.dialogType == 1) {
        apiUrl = '/eas/manage/goodsInfo/add/upload'
      } else if (state.dialogType == 2) {
        apiUrl = '/eas/manage/goodsInfo/modify/upload'
      }
      await axios.post(apiUrl, param, config).then(res => {
        if (res.data.code == '200') {
          successDeal('导入成功')
          context.emit('dialogClose', true)
          state.dialogFormVisible = false
        } else {
          warningDeal(res.data.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function deleteFile() {
      state.fileForm = {}
    }

    function submitHandle() {
      if (state.fileForm && state.fileForm.file) {
        uploadFile()
      } else {
        state.fileForm = {}
      }
    }

    function outArea() {
      api.areaDown({ responseType: "blob" }).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    return {
      ...toRefs(state),
      uploadInputRef,
      dialogShow,
      tabChange,
      dialogClose,
      templateDownLoad,
      uploadHandle,
      uploadChange,
      deleteFile,
      submitHandle,
      outArea,
    }
  }
}
</script>

<style lang="scss" scoped>
.content-box {
  .content-item {
    box-sizing: border-box;
    padding: 20px;
    background-color: #f8f9fa;
    margin-top: 20px;
    .upload-box {
      width: 100%;
      border: 1px dashed #dcdee0;
      box-sizing: border-box;
      padding: 40px;
      margin-top: 20px;
      text-align: center;
      background-color: #ffffff;
      .upload-file {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 20px;
        font-size: 12px;
        color: #a7a7a7;
        box-sizing: border-box;
        padding: 5px 10px;
        transition: all 0.3s;
        &:hover {
          background-color: rgba($color: #0081ff, $alpha: 0.8);
          color: #ffffff;
        }
        .delete-btn {
          cursor: pointer;
        }
      }
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>